using System;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using Framework.Cron;
using Framework.Interface;
using Framework.Singleton;
using UnityEngine;

namespace Framework.Manager
{
    public class CronManager : MonoSingleton<CronManager>, IMonoManager
    {
        private Dictionary<string, Cron.Cron> crons = new Dictionary<string, Cron.Cron>();

        private List<string> removeCrons = new List<string>();

        public async UniTask Initialize(Transform parent)
        {
            transform.SetParent(parent);
            crons.Clear();
            removeCrons.Clear();
            await UniTask.CompletedTask;
        }

        public void Shutdown()
        {
            crons.Clear();
            removeCrons.Clear();
        }

        private void Update()
        {
            foreach (KeyValuePair<string,Cron.Cron> cron in crons)
            {
                if (cron.Value.Update())
                {
                    removeCrons.Add(cron.Key);
                }
            }

            for (int i = 0; i < removeCrons.Count; i++)
            {
                crons.Remove(removeCrons[i]);
            }
            removeCrons.Clear();
        }

        public void Every(string key, float time, Action<object[]> handler, params object[] args)
        {
            if (!crons.TryGetValue(key, out Cron.Cron cron))
            {
                cron = new Cron.Cron(CronType.Every, time, handler, args);
                crons.Add(key, cron);
            }
        }

        public void After(string key, float time, Action<object[]> handler, params object[] args)
        {
            if (!crons.TryGetValue(key, out Cron.Cron cron))
            {
                cron = new Cron.Cron(CronType.After, time, handler, args);
                crons.Add(key, cron);
            } 
        }

        public void Remove(string name)
        {
            if (!crons.ContainsKey(name))
                return;
            
            crons.Remove(name);
        }
    }
}
